﻿CREATE PROCEDURE [dbo].[TempInventories_SelectNewArticles]
	@RangeReviewId INT
AS

declare @startDate DATE = (select FirstMonth from RangeReviews where Id = @RangeReviewId)
declare @totalMonths INT = (select TotalMonths from RangeReviews where Id = @RangeReviewId)
declare @startDatePY DATE = 
	(
		select CASE WHEN HasPriorYear = 1 THEN DATEADD(Month, -12, FirstMonth) ELSE FirstMonth END
		from RangeReviews where Id = @RangeReviewId
	)
declare @endDate DATE = DATEADD(Month, @totalMonths - 1, @startDate)

SELECT ArticleCode, Description, CategoryCode, CategoryId, EAN, Brand, Manufacturer
FROM TempInventories
WHERE ArticleId = 0 And Cost > 0
AND ((Date BETWEEN @startDatePY AND DATEADD(Month, @totalMonths - 1, @startDatePY)) OR (Date Between @startDate AND @endDate))
GROUP BY ArticleCode, Description, CategoryCode, CategoryId, EAN, Brand, Manufacturer